import type { ComponentMeta } from '@/definitions/type'
import type { RadioChangeEvent } from 'ant-design-vue'
import { EWebDesignerComponentBackground } from '@/api/designer/model'
import { useDesignStore } from '@/stores'
import { followThemeValue } from '@/utils/constants'
import { getInitialSpaceMobile, getInitialSpacePC, SpaceOption } from '@/utils/space'
import { computed, ref } from 'vue'
import { useUpload } from './useUpload'

export function useCompStyle<ComponentConfig extends ComponentMeta>() {
  const designStore = useDesignStore()
  // @ts-ignore
  const activeRender = computed<Nullable<ComponentConfig>>(() => designStore.activeRender)
  const noBgValue = '#ffffff'
  const initialBgColor = activeRender.value?.config.backgroundValue || noBgValue
  const spaceMobile = ref(getInitialSpaceMobile(activeRender.value!))
  const spacePC = ref(getInitialSpacePC(activeRender.value!))
  function handleBgChange(ev: RadioChangeEvent) {
    const nextValue = ev.target.value
    if (nextValue === EWebDesignerComponentBackground.主题色) {
      // @ts-ignore
      activeRender.value!.config.backgroundValue = followThemeValue.deep.toString()
    }
    else if (nextValue === EWebDesignerComponentBackground.无背景) {
      activeRender.value!.config.backgroundValue = noBgValue
    }
    else {
      activeRender.value!.config.backgroundValue = ''
    }
  }
  function handleSpaceModeChange(ev: RadioChangeEvent, platform: 'pc' | 'mobile') {
    const nextValue = ev.target.value
    if (nextValue === SpaceOption.default) {
      if (platform === 'mobile') {
        activeRender.value!.config.paddingLeft
            = activeRender.value!.config.paddingBottom
            = activeRender.value!.config.paddingTop 
            = activeRender.value!.config.paddingRight = 0
      }
      else if (platform === 'pc') {
        activeRender.value!.config.paddingLeftPC
            = activeRender.value!.config.paddingBottomPC
            = activeRender.value!.config.paddingTopPC 
            = activeRender.value!.config.paddingRightPC = 0
      }
    }
  }
  const { uploadAction: handleChooseFile } = useUpload({
    successHandler({ url }) {
      activeRender.value!.config.backgroundValue = url
    },
  })
  return {
    activeRender,
    initialBgColor,
    spaceMobile,
    spacePC,
    handleBgChange,
    handleSpaceModeChange,
    handleChooseFile,
  }
}
